<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-if="false" v-model="listQuery.lineNumber" :placeholder="$t('equipment.lineNumber')" class="filter-item" style="width: 200px" @change="handleLineSelect">
        <el-option v-for="item in lineOptions" :key="item.lineNumber" :label="item.lineName" :value="item.lineNumber" />
      </el-select>
      <el-select v-model="listQuery.stationNumber" :placeholder="$t('equipment.stationNumber')" class="filter-item" clearable="" style="width: 200px">
        <el-option v-for="station in stationOptions" :key="station.stationName" :label="station.stationName+'_'+station.stationNumber" :value="station.stationNumber" />
      </el-select>
      <el-select v-model="listQuery.alarmType" :placeholder="$t('equipment.alarmType')" class="filter-item" clearable="" style="width: 200px" @change="handleFilter">
        <el-option v-for="alarm in alarmOptions" :key="alarm.key" :label="alarm.label" :value="alarm.key" />
      </el-select>
      <el-date-picker v-model="listQuery.startTime" value-format="yyyy-MM-dd" format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('common.startDate')" class="filter-item" />
      <el-date-picker v-model="listQuery.endTime" value-format="yyyy-MM-dd" format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('common.endDate')" class="filter-item" />
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('common.search') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('common.export') }}
      </el-button>
    </div>
    <!-- 主界面数据 -->
    <el-table
      ref="dragTable"
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      :header-row-style="{color: 'black'}"
      :header-cell-style="{background: 'lightBlue'}"
      border
      fit
      row-key="id"
      highlight-current-row
      style="width: 100%;"
    >
      <!-- <el-table-column :label="$t('equipment.lineNumber')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.lineNumber }}</span>
        </template>
      </el-table-column> -->
      <el-table-column :label="$t('equipment.stationNumber')" width="130px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.stationNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.stationName')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.stationName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.alarmType')" width="100px" align="center">
        <template slot-scope="{row}">
          <el-tag type="danger"> {{ row.alarmType }} </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.creatTime')" width="240px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.creatTime }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.message')" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.message }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.remark')" width="150px" align="center">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">
            <i :style="{color:row.remark === ''?'red':'green'}" class="el-icon-edit" />
          </span>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <bar-chart v-if="total>0" height="376px" :chart-data="barChartData" />
    <!-- 新建和更新对话框 -->
    <el-dialog v-el-drag-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 600px; margin-left:50px;">
        <el-form-item :label="$t('equipment.remark')" prop="remark">
          <el-input
            v-model="temp.remark"
            :placeholder="$t('msg.CHARACTER_LESS_THAN')+200"
            :autosize="{ minRows: 5, maxRows: 10}"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getEquipmentAlarms, creatAlarmRemark, getLineList, getStationListEx } from '@/api/equipment'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import i18n from '@/lang'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import BarChart from '@/components/Charts/BarChartAlarm.vue'

export default {
  name: 'EquipmentAlarm',
  components: {
    BarChart,
    Pagination
  },
  directives: { waves, elDragDialog },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    const validateRemark = (rule, value, callback) => {
      if (value.length > 200) {
        callback(new Error('character length < 200'))
      } else {
        callback()
      }
    }
    return {
      editRight: true,
      tableKey: 0,
      list: [],
      newList: [],
      sortable: null,
      lineOptions: [],
      stationOptions: [],
      alarmList: [],
      barChartData: {
        dimensions: ['stationName', 'warn', 'info', 'error'],
        alarmList: []
      },
      // 任务u状态
      alarmOptions: [{ label: i18n.t('common.tip'), key: 'info', color: 'black' },
        { label: i18n.t('common.warn'), key: 'warn', color: 'blue' },
        { label: i18n.t('common.error'), key: 'error', color: 'red' }],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        state: 0,
        lineNumber: '',
        stationNumber: '',
        alarmType: '',
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+processNumber'
      },
      showReviewer: false,
      showRemark: false,
      temp: {
        alarmId: '',
        lineNumber: '',
        stationNumber: '',
        alarmType: '',
        message: '',
        status: 0,
        remark: '',
        creatTime: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew')
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        remark: [{ required: true, trigger: 'blur', validator: validateRemark }],
        resultCode: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        resultName: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }]
      },
      downloadLoading: false,
      searchLoading: {
        director: false
      },
      searchDialogStatus: '',
      searchDialogFormVisible: {
        director: false
      }
    }
  },
  created() {
    this.editRight = (this.$store.getters.roles === 'admin' || this.$store.getters.roles === 'administrator')
    this.listQuery.lineNumber = this.$store.getters.lineNumber
    this.getLineOptions()
    this.getStationOptions()
  },
  methods: {
    timestepToolTip(index) {
      return index + '%'
    },
    formatDateTime(date) {
      return date.substring(0, 10)
    },
    // 获取线体清单
    getLineOptions() {
      this.listLoading = true
      getLineList(this.listQuery).then(response => {
        this.lineOptions = response.data.lines
        this.listLoading = false
      })
    },
    // 获取工艺流程选项
    getStationOptions() {
      this.listLoading = true
      this.stationOptions = []
      getStationListEx(this.listQuery).then(response => {
        this.stationOptions = response.data.stations
        this.listLoading = false
      })
    },
    // 判断线体ID是否为空
    isEmptyLineId: function() {
      var ret = (this.listQuery.lineNumber === undefined || this.listQuery.lineNumber === '')
      if (ret) {
        this.$notify({
          title: this.$i18n.t('common.tip'),
          message: i18n.t('msg.NO_LINE_SELECTED'),
          type: 'success',
          duration: 2000
        })
      }
      return ret
    },
    // 获取清单
    getList() {
      if (this.isEmptyLineId() === false) {
        this.listLoading = true
        getEquipmentAlarms(this.listQuery).then(response => {
          this.total = response.data.total
          this.list = []
          this.listLoading = false
          if (this.total > 0) {
            this.list = response.data.alarms
            this.list.forEach(e => {
              this.stationOptions.forEach(station => {
                if (station.stationNumber === e.stationNumber) {
                  e.stationName = station.stationName
                  return
                }
              })
            })
            this.alarmList = this.formatDatas(this.list)
            this.alarmList.sort(function(a, b) {
              if (a.info < b.info) {
                return 1
              }
              if (a.info > b.info) {
                return -1
              }
              if (a.info === b.info) {
                return 0
              }
            })
            this.barChartData.alarmList = this.alarmList
          } else {
            this.barChartData.alarmList = []
          }
        })
      }
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleLineSelect() {
      this.listQuery.stationNumber = ''
      this.processOptions = []
      this.List = []
      getStationListEx(this.listQuery).then(response => {
        this.stationOptions = response.data.stations
      })
    },
    // 点击编辑按钮
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据到数据库
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          creatAlarmRemark(this.temp).then(response => {
            const index = this.list.findIndex(v => v.alarmId === this.temp.alarmId)
            this.list.splice(index, 1, response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.UPDATE_SUCCESS'),
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 下载所有导出信息
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          i18n.t('equipment.lineNumber'),
          i18n.t('equipment.stationNumber'),
          i18n.t('equipment.alarmType'),
          i18n.t('equipment.message'),
          i18n.t('equipment.remark'),
          i18n.t('equipment.creatTime')]
        const filterVal = ['lineNumber', 'stationNumber', 'alarmType', 'message', 'remark', 'creatTime']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '报警信息' + parseTime(Date.now(), '{y}{m}{d}{h}{i}{s}')
        })
        this.downloadLoading = false
      })
    },
    // 过滤相关信息
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    // 处理后台拿到的数据
    formatDatas(arr) {
      var hash = []
      for (var i = 0; i < arr.length; i++) {
        for (var j = i + 1; j < arr.length; j++) {
          if (arr[i].stationNumber === arr[j].stationNumber && arr[i].alarmType === arr[j].alarmType) {
            ++i
            j = i
          }
        }
        arr[i].num = 0
        hash.push(arr[i])
      }
      // 第二步，统计重复个数
      hash.forEach(item => {
        arr.forEach(dd => {
          if (item.stationNumber === dd.stationNumber && item.alarmType === dd.alarmType) {
            item.num++
          }
        })
      })
      const arr1 = []
      const arr2 = []
      hash.forEach(item => {
        if (arr1.indexOf(item.stationNumber) < 0) {
          arr1.push(item.stationName)
          arr2.push(item)
          item[item.alarmType] = item.num
        } else {
          arr2.forEach(itmes => {
            if (itmes.stationNumber === item.stationNumber) {
              itmes[item.alarmType] = item.num
            }
          })
        }
      })
      return arr2
    }
  }
}
</script>
<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  height: 800px;
  background-color: white;
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px x0;
    //margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
